package com.blue.gateway.config.filters.global;

import com.blue.common.third.generator.id.IDGenerator;
import com.blue.gateway.bean.constants.GatewayHeaderKey;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 3.全局过滤器
 * ServerHttpRequest、ServerWebExchange都是不可变实例，
 * 如果修改，需要执行mutate方法重新获取实例
 *
 * @author liulei
 * @version 1.0
 */
@Configuration
public class RequestNoGenerateFilter implements GlobalFilter, Ordered {

    private static Logger log = LogManager.getLogger(RequestNoGenerateFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("3.过滤器链-添加请求序列号，对请求进行分布式序列号处理");
        ServerHttpRequest request = exchange.getRequest();
        // 该实例为只读实例，如果直接操作add等方法会报错
        HttpHeaders headers = request.getHeaders();
        String serialNum = headers.getFirst(GatewayHeaderKey.REQUEST_NO);
        if (StringUtils.isEmpty(serialNum)) {
            serialNum = IDGenerator.getIdStr();
            ServerHttpRequest newReq = request.mutate()
                    .header(GatewayHeaderKey.REQUEST_NO, serialNum)
                    .build();
            ServerWebExchange webExchange = exchange.mutate().request(newReq).build();
            return chain.filter(webExchange);
        }
        log.info("已存在网关唯一标识序列号： [{}]", serialNum);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -80;
    }

}
